package org.luosl.webmagicx.utils

import java.util.concurrent.locks.{Lock, ReentrantLock}

/**
  * Created by luosl on 2018/3/16.
  */
object ResourceUtils {

  /**
    * 自动释放锁操作
    * @param lock 锁
    * @param op 操作
    * @tparam T 返回值类型
    * @return
    */
  def withLock[T](lock:Lock)(op:Unit => T):T = {
    lock.lock()
    try{
      op()
    }finally lock.unlock()
  }

  /**
    * 自动关闭操作
    * @param closeable closeable
    * @param op op
    * @tparam T T
    * @tparam V V
    * @return
    */
  def withClose[T <: AutoCloseable, V](closeable :T)(op: T => V):V = {
    try{
      op(closeable)
    }finally {
      if( null != closeable) closeable.close()
    }
  }

}
